package one.stand.controller;

import com.jmp.api.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.im.ImNotifyClient;
import one.stand.dto.UserDto;
import one.stand.enums.LoginEnum;
import one.stand.model.BusinessCard;
import one.stand.model.ResultModel;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.MessageMsgService;
import one.stand.service.user.TokenService;
import one.stand.service.user.UserAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 云信控制器
 */
@RequestMapping("/yunxin")
@RestController
public class YunxinController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private MessageMsgService messageMsgService;

    @GetMapping("info")
    @SecurityAuthCheck
    public ResultModel<YunxinInfoResponse> info(@RequestAttribute YunxinInfoRequest request) {
        BusinessCard businessCardModel = businessCardBaseService.getByUserId(request.getTargetId());
        YunxinInfoResponse response;
        if (Objects.nonNull(businessCardModel)) {
            response = YunxinInfoResponse.builder()
                    .wxCode(businessCardModel.getPersonalWx())
                    .phone(businessCardModel.getPhone())
                    .build();
        } else {
            UserDto user = userAdminService.get(request.getTargetId());
            response = YunxinInfoResponse.builder()
                    .phone(user.getPhone())
                    .build();
        }
        return ResultModel.success(response);
    }

    @PostMapping("read")
    @SecurityAuthCheck
    public ResultModel read(@RequestAttribute YunxinReadRequest request) {
        messageMsgService.removeUnreadNum(String.valueOf(request.getId()), request.getTargetId(), ImNotifyClient.TYPE);

        return ResultModel.success();
    }

    @PostMapping("logout")
    @SecurityAuthCheck
    public ResultModel logout(@RequestAttribute YunxinLogoutRequest request) {
        tokenService.removeLoginStatus(request.getId(), LoginEnum.CRM);
        return ResultModel.success();
    }

    @PostMapping("login")
    @SecurityAuthCheck
    public ResultModel<YunxinLoginResponse> login(@RequestAttribute YunxinLogoutRequest request) {
        tokenService.saveLoginStatus(request.getId(), LoginEnum.CRM.getCode());

        Integer unReadMsg = messageMsgService.getUnreadNumAll(String.valueOf(request.getId()), ImNotifyClient.TYPE);
        YunxinLoginResponse response = YunxinLoginResponse.builder()
                .unReadMsg(unReadMsg)
                .build();
        return ResultModel.success(response);
    }
}
